package 剑指offer;

import java.math.BigInteger;

/**
 * Created by lenovo】 on 2017/3/22.
 * 输入一个正整数数组，把数组里所有数字拼接起来排成一个数，
 * 打印能拼接出的所有数字中最小的一个。例如输入数组{3，32，321}，则打印出这三个数字能排成的最小数字为321323。
 */
public class PrintMinNumber {
    public String PrintMinNumber(int [] numbers) {
        int len = numbers.length;
        int count = len - 1;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < count - i; j++) {
                BigInteger numbersDirect = joinStringAsInt(numbers[j], numbers[j+1]);
                BigInteger numbersReverse = joinStringAsInt(numbers[j+1], numbers[j]);
                int res = numbersDirect.compareTo(numbersReverse);
                if (res > 0) {
                    numbers[j] = numbers[j] ^ numbers[j+1];
                    numbers[j+1] = numbers[j] ^ numbers[j+1];
                    numbers[j] = numbers[j] ^ numbers[j+1];
                }
            }
        }
        return joinStringAsString(numbers);
    }

    public BigInteger joinStringAsInt(Object ...obj) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Object o : obj) {
            stringBuilder.append(o.toString());
        }

        return new BigInteger(stringBuilder.toString());
    }
    public String joinStringAsString(int ...obj) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Object o : obj) {
            stringBuilder.append(o.toString());
        }
        return stringBuilder.toString();
    }
}
